<template>
  <div :style="'width: 100%; max-width: ' + props.width + 'px;height: ' + props.height + 'px'">
    <span v-if="(inputDisabled || props.showText) && (props.modelValue || '') !== ''" class="image-box">
      <el-image
        v-if="imageUrl !== ''"
        preview-teleported
        :src="imageUrl"
        :preview-src-list="[imageUrl]"
        style="width:100%;height:100%"
        fit="scale-down"
      />
    </span>
    <span v-else-if="!inputDisabled" class="image-edit-box">
      <el-upload :class="['cm-image', {'is-disabled': inputDisabled}]" action=""
        :disabled="inputDisabled"
        :http-request = "handleUpload"
        :show-file-list="false"
        :accept="'image/*'"
        :before-upload="handleBeforeUpload"
      >
        <i v-if="loading" class="fa fa-regular fa-spinner fa-spin loading-icon"></i>
        <span v-else-if="imageUrl && !loading">
          <img :src="imageUrl" alt />
        </span>
        <i v-else class="fa fa-plus plus-icon"></i>
      </el-upload>
    </span>
  </div>
</template>

<script setup>
import {ref, watch, onMounted, nextTick} from 'vue'
import {ElMessage, useDisabled, useFormItem} from "element-plus";
import api from "@/http/api";

const emit = defineEmits(['update:modelValue', 'change']);
const props = defineProps({
  modelValue: [Number, String],
  width: {
    type: Number,
    default: 100
  },
  height: {
    type: Number,
    default: 100
  },
  showText: Boolean
});

const loading = ref(true);
const fileId = ref('');
const imageUrl = ref('');
const inputDisabled = useDisabled();
const formItem = useFormItem();

const handleUpload = (data) => {
  return new Promise((resolve, reject) => {
    api.upload({'file': data.file}).then((res) => {
      loading.value = false;
      fileId.value = res.data.id;
      imageUrl.value = URL.createObjectURL(data.file);
      emit('update:modelValue', res.data.id);
      nextTick(() => {
        if (formItem && formItem.formItem) {
          formItem.formItem.validate('change');
        }
      });
      resolve();
    }).catch(() => {
      loading.value = false;
      reject();
    });
  });
};

const handleBeforeUpload = (file) => {
  if (loading.value) {
    ElMessage.error("图片正在上传中，请稍候再试！");
    return false;
  }
  loading.value = true;

  let isImage = file.type.includes("image");
  if (!isImage) {
    loading.value = false;
    ElMessage.error("上传文件类型必须是图片!");
  }
  let isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    loading.value = false;
    ElMessage.error("上传图片大小不能超过 2MB!");
  }
  return isImage && isLt2M;
};

const loadData = () => {
  if (typeof props.modelValue !== "undefined" && props.modelValue != null && props.modelValue !== "") {
    fileId.value = props.modelValue;
    loading.value = true;
    api.download(props.modelValue).then((res) => {
      loading.value = false;
      imageUrl.value = URL.createObjectURL(new Blob([res.data]));
    }).catch(() => {
      loading.value = false;
    });
  } else {
    loading.value = false;
    fileId.value = '';
    imageUrl.value = '';
  }
};

watch(() => props.modelValue, (newVal) => {
  if (newVal === undefined || newVal == null || newVal === ''
      || fileId.value === undefined || fileId.value === null || fileId.value === ''
      || newVal !== fileId.value) {
    loadData();
  }
});

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.cm-image {
  height: 100%;
  width: 100%;
  flex: 1;
  justify-content: center;
  align-items: center;
  display: flex;
  border: 1px dashed #c2c2c2;
}
.cm-image :deep(.el-upload) {
  display: flex;
  text-align: center;
  cursor: pointer;
  outline: 0;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
.cm-image :deep(.el-upload span) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.cm-image:not(.is-disabled) :deep(.el-upload) {
  cursor: pointer;
}
.cm-image:not(.is-disabled) :deep(.el-upload:hover) {
  border-color: #409EFF;
}
.loading-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
}
.plus-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
}
.cm-image img {
  max-width: 100%;
  max-height: 100%;
}
.image-box {
  border: 1px dashed #d9d9d9;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.image-box img {
  max-width: 100%;
  max-height: 100%;
}
.cm-image :deep(.el-upload:after) {
  display: block;
  margin-top: 100%;
  content: ""
}
</style>